// app.js
// var push = require('./utils/pushsdk.js');

import { request, setLoginUrl, extend, constants, Uuid } from './sdk/index'
import { formatPrice } from './utils/util'
import { config } from './config'
import { requestApi } from './api'

// 小神推
// var fundebug = require('./utils/fundebug.0.0.3.min.js')
// fundebug.apikey = 'b79963b3269ca84253d58aab2c484bdc32affedb342d9026c3761e2dd1bfaff7'
// fundebug.appVersion = constants.DIV
// fundebug.releaseStage = 'production'

// let metaData = {}

// try {
// 	metaData = wx.getSystemInfoSync()
// } catch (e) {
// 	//
// }

// fundebug.metaData = metaData

// 支持打开APP的场景值
const launchAppScene = 1036
const launchAppSceneExtra = [1089, 1090]
// const launchAppFailTips = '您可以关注“OFashion迷橙”公众号'
const launchAppFailTips = '请下载“OFashion迷橙”APP'

App({
  data: {
    channel: 'wx_xcx',
    api_url: config.apiUrl,
    upload_url: config.uploadUrl,
    supportLaunchApp: false, // 是否支持打开APP
    launchAppFailTips: launchAppFailTips,
    h: 0,
    newUserPop: null,  // 新用户优惠 status: 0没有弹窗 1新用户 2老用户 coupon_list: 优惠券ID
    searchBrands: [],
    congifData: null
  },
  globalData: {
    StatusBar: '',
    openId: '',
    CustomBar: '',
  },



  onLaunch(options) {
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // console.log(res.hasUpdate)
      if (res.hasUpdate) {
        updateManager.onUpdateReady(function () {
          wx.showModal({
            title: '更新提示',
            content: '新版本已准备好，是否重启应用？',
            success: function (res) {
              if (res.confirm) {
                updateManager.applyUpdate()
              }
            }
          })
        })
      }
    })
    wx.getSystemInfo({
      success: (e) => {

        this.globalData.StatusBar = e.statusBarHeight;
        let capsule = wx.getMenuButtonBoundingClientRect();
        if (capsule) {
          this.globalData.Custom = capsule;
          this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
        } else {
          this.globalData.CustomBar = e.statusBarHeight + 50;
        }
      }
    })
    // console.info('app onLaunch')
    // console.info('options', options)
    // 配置登录url
    setLoginUrl(config.loginUrl)

    // 来源为小程序
    // if (options && options.referrerInfo && options.referrerInfo.appId) {
    //   wx.setStorage({
    //     key: 'referrerInfo',
    //     data: options.referrerInfo,
    //   })
    //   wx.showModal({
    //     title: '提示',
    //     showCancel: false,
    //     content: options.referrerInfo.extraData.foo,
    //   })
    // }

    // 获取状态栏高度
    const { statusBarHeight, windowWidth } = wx.getSystemInfoSync();
    // 得到右上角菜单的位置尺寸
    const { top, height } = wx.getMenuButtonBoundingClientRect();

    const navBarHeight = height + (top - statusBarHeight) * 2;

    // 计算状态栏与导航栏的总高度
    const statusNavBarHeight = statusBarHeight + navBarHeight;

    this.data.h = statusNavBarHeight;
    this.data.top = top;
    this.data.height = height;
    this.data.windowWidth = windowWidth;

    // app.json 里选项 window 已配置竖屏展示 pageOrientation: portrait
    this.getNewUserPop();
  },

  onShow(options) {
    // console.info('app onShow')
    // console.info('options', options)

    // 生成设备唯一标识
    if (!Uuid.get()) {
      Uuid.set()
    }

    let supportLaunchApp = false

    // TODO 逻辑剥离出onShow方法
    // 该设备及场景是否支持打开APP
    if (wx.canIUse('button.open-type.launchApp')) {
      if (options.scene == launchAppScene) {
        supportLaunchApp = true

        wx.setStorage({
          key: 'supportLaunchApp',
          data: supportLaunchApp,
        })
      } else if (launchAppSceneExtra.indexOf(options.scene) != -1) {
        try {
          supportLaunchApp = wx.getStorageSync('supportLaunchApp')
        } catch (e) {
          // 
        }
      } else {
        wx.setStorage({
          key: 'supportLaunchApp',
          data: false,
        })
      }
    }

    this.data.supportLaunchApp = supportLaunchApp;
  },

  onError() {
    // 
  },

  // 判断是否登录
  toLogin: function () {
    let userinfo = wx.getStorageSync('userinfo') || {}

    if (!userinfo.mobile_phone) {
      wx.navigateTo({
        url: '/pages/account/login/login',
      })

      return false
    }

    return true
  },

  // 判断预约活动是否登录
  toActivityLogin: function () {
    let userinfo = wx.getStorageSync('userinfo') || {}

    if (!userinfo.mobile_phone) {
      wx.redirectTo({
        url: '/pages/account/login/login',
      })

      return false
    }

    return true
  },

  request(options, success, fail, complete) {
    const channel = this.data.channel

    request(extend(true, {
      method: 'GET',
      data: {
        channel,
      },
      // 请求之前是否需要授权登陆，如果该项指定为 true，会在请求之前进行授权登录
      login: false,

      success(res) {
        if (res.data && res.data.original && res.data.original.status == 'fail') {
          return fail && fail(res.data.original.msg)
        }

        success && success(res.data)
      },

      fail(error) {
        // request:fail 可能是网络原因
        fail && fail(error.type ? ((error.type === 200 ? '' : error.type) + error.message) : (error.errMsg ? error.errMsg : error))
      },

      complete() {
        complete && complete()
      }
    }, options))
  },

  getOpenId(){
    return new Promise((resolve, reject) => {
      let openId = wx.getStorageSync('openId');
      if(openId){
        resolve(openId)
      }else{
        wx.login({
          success : (res) => {
            let obj = {
              url: requestApi.getKey,
              method: 'POST',
              login: false,
              data: {
                js_code: res.code
              },
            }
            this.request(obj, (data) => {
              if (data.original.ret_code == 200) {
                wx.setStorageSync('openId', data.original.data.openid)
                resolve(data.original.data.openid)
              }
            }, (error) => {
              reject(error)
            })
          }
        })
      }
      
    })
  },

  getSellerId(openid) {
    return new Promise((resolve, reject) => {
      this.request({
        url: 'https://moses.ofashion.com.cn/wechat_get_user_behavior',
        data: {
          openid: openid
        },
      }, res => {
        if(res.original.ret_code == 200){
          resolve(res.original.data.seller_uid)
        }
      }, err=>{})
    })
    
  },

  addUseBbehavior(openid, seller_uid) {
    return new Promise((resolve, reject) => {
      this.request({
        url: 'https://moses.ofashion.com.cn/wechat_add_user_behavior',
        data: {
          openid: openid,
          seller_uid
        },
      }, res => {
        if(res.original.ret_code == 200){
          resolve(res.original)
        }
      }, err=>{})
    })
    
  },

  // 获取接口下发的配置信息
  getRemoteConfigData() {
    let userinfo = wx.getStorageSync('userinfo') || {};
    this.request({
      url: requestApi.gethotconfig,
      data: {
        login_uid: userinfo.uid,
        is_new_ver: true,
      },
    }, (data) => {
      if (data.original.ret_code == 200) {
        this.data.configData = data.original.data;

        // 是否有浮层活动
        if (this.configDataCallback) {
          this.configDataCallback(this.data.configData);
        }
      }
    }, (error) => {
      // 
    })
  },

  // 获取接口下发的配置信息
  getNewUserPop() {
    const { channel } = this.data;

    this.request({
      url: requestApi.showNewUserPop,
      data: {
        is_new_ver: true,
        channel: channel
      },
    }, (data) => {
      const coupon_list = data.original.data.coupon_list.map(item => item.coupon_no);

      this.data.newUserPop = {
        status: data.original.data.status || 0,
        price: formatPrice(data.original.data.pop.price / 100) || 0,
        goods_imgs: data.original.data.pop.goods_imgs || [],
        img_desc: data.original.data.pop.img_desc || [],
        coupon_no: coupon_list.join(',') || ''
      };

      if (this.newUserCallback) {
        this.newUserCallback(this.data.newUserPop);
      }
    }, (error) => {
      // 
    })
  },

  // 通过请求接口，将锻炼转为长链，并取出其中的参数
  shortUrlToLong(url, callback) {
    let resArr = []
    let resObj = {}
    this.request({
      url: requestApi.shortToLongUrl,
      method: 'POST',
      login: false,
      data: {
        short_link: url
      },
    }, (data) => {
      let resUrl = data.original.data.original_link
      let num = resUrl.indexOf('?')
      let key, value

      resUrl = resUrl.substr(num + 1)
      resArr = resUrl.split('&')

      for (let i = 0; i < resArr.length; i++) {
        num = resArr[i].indexOf("=")

        if (num > 0) {
          key = resArr[i].substr(0, num)
          value = resArr[i].substr(num + 1)
          resObj[key] = value
        }
      }
      callback(resObj)
    })
  }
})